package com.example.leo.mycharmingstudent.a0916;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.leo.mycharmingstudent.R;

import java.util.List;

/**
 * Created by Leo on 2020/9/16.
 */

public class MyHeroAdapter extends BaseAdapter {

    private Context mContext;
    private List<HeroEntity> mHeroList;

    public MyHeroAdapter(Context context, List<HeroEntity> heroList) {
        this.mContext = context;
        this.mHeroList = heroList;
    }

    /**
     * 返回条目数量
     * 要求：不多不少刚刚好
     *
     * @return
     */
    @Override
    public int getCount() {
        return mHeroList.size();
    }

    /**
     * 获取position位置条目的信息
     *
     * @param position
     * @return
     */
    @Override
    public HeroEntity getItem(int position) {
        return mHeroList.get(position);
    }

    /**
     * 返回itemId
     * 标准范式，返回position
     * 或者，想返回啥返回啥，唯一就行
     *
     * @param position
     * @return
     */
    @Override
    public long getItemId(int position) {
        return position;
    }

    /**
     * 返回条目的View
     *
     * @param position
     * @param convertView 可以复用的条目View，注意判空
     * @param parent
     * @return
     */
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            //第一步，获取LayoutInflater对象，通过别人介绍
            LayoutInflater inflater = LayoutInflater.from(mContext);
            //第二步，通过LayoutInflater对象填充布局（创建View）
            convertView = inflater.inflate(R.layout.item_cardview_listview_activity, null, false);

            holder = new ViewHolder();
            //第三步，找控件
            holder.ivHero = convertView.findViewById(R.id.iv_hero_item_cardview);
            holder.tvName = convertView.findViewById(R.id.tv_hero_name_item_cardview);
            holder.tvIntroduce = convertView.findViewById(R.id.tv_hero_introduce_item_cardview);

            //千万记得  ViewHolder和convertView进行绑定
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        //第四步，获取当前位置的英雄信息
        HeroEntity item = getItem(position);
        //第五步，给控件设置数据
        Glide.with(mContext).load(item.getImageResource()).into(holder.ivHero);
        holder.tvName.setText(item.getName());
        holder.tvIntroduce.setText(item.getIntroduce());
        return convertView;
    }

    /**
     * ViewHolder的作用：
     * 避免findViewById浪费太多时间，
     * 使用ViewHolder内存存储一下控件
     * <p>
     * ViewHolder需要和View(convertView)进行绑定
     * 怎么绑定呢？
     * setTag
     */
    public static class ViewHolder {
        public ImageView ivHero;
        public TextView tvName;
        public TextView tvIntroduce;
    }
}
